#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "mqtt_client.h"
#include "esp_event.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "cJSON.h"

#include "sdkconfig.h"
#include "freertos/queue.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_log.h"
#include <sys/time.h>
#include "esp_sntp.h"

#include "sntp_time.h"


char* state_p = "normal";
char to_mysql_message[200]="";
char time_date[60]="";
extern int position_array[5];
extern int temperature_array[5];
extern int volatge_array[5];
extern esp_mqtt_client_handle_t emcht;
void my_function(void)
{
    printf("Hello from my_function\n");
}

static struct tm timeinfo;

void esp_initialize_sntp(void)
{
    esp_sntp_setoperatingmode(SNTP_OPMODE_POLL);    // 设置单播模式
    esp_sntp_setservername(0, "pool.ntp.org");
    esp_sntp_setservername(1, "cn.pool.ntp.org");
    esp_sntp_setservername(2, "ntp1.aliyun.com");
    setenv("TZ", "CST-8", 1);                   //东八区
    esp_sntp_init();                                //初始化
}

/**
 * @brief 启动sntp获取网络时间
 * @param 无
 * @return 无
 * @note tm_mon: 从0开始            tm_year: 距离1900年的差值，默认是70
 *       tm_yday: 一年的过去的天数   tm_isdst: 是否为夏时制
 */
void sntp_task(void)
{
        time_t now;
        time(&now);                         // 获取网络时间, 64bit的秒计数 
        tzset();                            // 更新本地C库时间
        localtime_r(&now, &timeinfo);       // 转换成具体的时间参数
        // strftime(strftime_buf, sizeof(strftime_buf), "%c", &amp;timeinfo);
        // ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);
        printf("%4d-%02d-%02d %02d:%02d:%02d week:%d\r\n", timeinfo.tm_year + 1900, timeinfo.tm_mon + 1,timeinfo.tm_mday, timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec, timeinfo.tm_wday);

        sprintf(time_date, "%4d-%02d-%02d %02d:%02d:%02d week:%d", timeinfo.tm_year + 1900, timeinfo.tm_mon + 1,timeinfo.tm_mday, timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec, timeinfo.tm_wday);
        for (int mysql_id = 0; mysql_id < 5; mysql_id++)
        {
          sprintf(to_mysql_message, \
            "{\"time_date\":\"%s\",\"id\":%d,\"temperature\":%d,\"volatge\":%.03f,\"state\":\"%s\"}",\
            time_date,mysql_id+1,temperature_array[mysql_id],(float)volatge_array[mysql_id]*0.001,state_p);
            esp_mqtt_client_publish(emcht,"to_mysql",to_mysql_message,strlen(to_mysql_message),1,0);
          memset(to_mysql_message, 0, sizeof(to_mysql_message));
          memset(time_date, 0, sizeof(time_date));
        }
    
}
struct tm* get_time(void)
{
    return &timeinfo;
}